package com.gzc.just.play.last.war.common.serializer;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Java内置序列化实现类，实现MessageSerializer接口
 * 提供基于Java序列化的消息序列化/反序列化功能
 */
public class JavaSerializer implements MessageSerializer {
    private static final Logger logger = LoggerFactory.getLogger(JavaSerializer.class);
    
    private final ObjectMapper objectMapper;
    
    public JavaSerializer() {
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public String serialize(Object message) {
        if (message == null) {
            return null;
        }
        
        try {
            // 使用Jackson将对象转换为JSON字符串
            return objectMapper.writeValueAsString(message);
        } catch (Exception e) {
            logger.error("Java序列化错误", e);
            return null;
        }
    }

    @Override
    public Object deserialize(String json, int messageId) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        
        try {
            // 使用Jackson从JSON反序列化
            Class<?> messageClass = getMessageClass(messageId);
            if (messageClass != null) {
                return objectMapper.readValue(json, messageClass);
            }
            return null;
        } catch (Exception e) {
            logger.error("Java反序列化错误: messageId={}", messageId, e);
            return null;
        }
    }

    @Override
    public byte[] serializeToBytes(Object message) {
        if (message == null) {
            return null;
        }
        
        try {
            // 使用Java内置序列化
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                oos.writeObject(message);
                oos.flush();
                return baos.toByteArray();
            }
        } catch (IOException e) {
            logger.error("Java序列化到字节数组错误", e);
            return null;
        }
    }

    @Override
    public Object deserializeFromBytes(byte[] bytes, int messageId) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        
        try {
            // 使用Java内置反序列化
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            try (ObjectInputStream ois = new ObjectInputStream(bais)) {
                return ois.readObject();
            }
        } catch (Exception e) {
            logger.error("Java反序列化从字节数组错误: messageId={}", messageId, e);
            return null;
        }
    }
    
    /**
     * 根据消息ID获取相应的消息类
     */
    private Class<?> getMessageClass(int messageId) {
        // 由于Java序列化不依赖具体类，这里只返回基本类型
        // 实际使用中可能需要根据具体需求实现
        return Object.class;
    }
}
